import router from '~/router/index'
import Layout from '~/layout/index.vue'
import type { RouteRecordRaw } from 'vue-router'
import { enable as enableStatic, routes as staticsRoutes } from '~/router/statics'

const modules = import.meta.glob('../views/*/*.vue')

/**
 * 注册路由，并返回菜单数据
 */
export function initRouteAndNav(funcs: Array<UaaAuthority>): Array<Menu> {
  // 根据配置读取
  if (enableStatic) {
    return realInitRouteAndNav(staticsRoutes)
  } else {
    return realInitRouteAndNav(funcs)
  }
}

function realInitRouteAndNav(funcs: Array<UaaAuthority>): Array<Menu> {
  const accessRouters = funcs.filter(func => func.type == 1 || func.type == 0)

  let genRoute: RouteRecordRaw = {
    name: 'System',
    path: '/system',
    component: Layout,
    children: []
  }

  accessRouters?.map(c => {
    if (c.parentId > 0) {
      const file = c.routeFile && c.routeFile.indexOf('/') == 0 ? c.routeFile : `/${c.routeFile}`

      const childGenRoute: RouteRecordRaw = {
        name: c.routeName || c.name,
        path: c.routePath || 'default',
        component: modules[`../views${file}.vue`],
        meta: {
          keepAlive: c.keepAlive,
          title: c.name,
          icon: c.menuIcon,
          menuDisplay: c.menuDisplay,
          id: c.id,
          pid: c.parentId
        }
      }
      genRoute.children?.push(childGenRoute)
    }
  })
  router.addRoute(genRoute)
  return buildMenuTree(
    accessRouters.filter(r => r.menuDisplay),
    0
  )
}

function buildMenuTree(routers: Array<UaaAuthority>, parentId: number): Array<Menu> {
  let trees = []
  for (const func of routers) {
    if (func.parentId == parentId) {
      const menu: Menu = {
        id: func.id,
        icon: func.menuIcon,
        index: func.routeName,
        title: func.name,
        path: func.routePath
      }
      menu.children = buildMenuTree(routers, func.id)
      trees.push(menu)
    }
  }
  return trees
}

/**
 * 深度查找
 * @param treeData
 * @param value
 * @param key 要查找的字段
 * @returns
 */
export function deepFind(treeData: any, value: any, key: string) {
  for (const data of treeData) {
    if (data[key] == value) {
      return true
    }
    if (data.children && data.children.length > 0) {
      if (deepFind(data.children, value, key)) {
        return true
      }
    }
  }
  return false
}

/**
 * 用户是否具有相关权限
 * @param auth
 * @param strict 是否为严格模式，严格模式下auth不能未null，非严格模式下auth为null表示具有相关权限
 * @returns boolean
 */
export function hasAuth(auth: string | undefined | null, strict?: boolean) {
  const store = useAppStore()
  const user = store.user
  if (user && user.authorities) {
    if (strict === false && !auth) return true
    return user.authorities.find(item => item.authority == auth) ? true : false
  }
  return false
}

/**
 * 在树中查找相应的数据
 * @param {*} treeData
 * @param {*} attr
 * @param {*} value
 * @returns
 */
export function searchTree(treeData: any, attr: string, value: any): any {
  if (treeData == null) return {}
  for (const data of treeData) {
    if (data[attr] == value) {
      return data
    }
    if (data.children && data.children.length > 0) {
      const result = searchTree(data.children, attr, value)
      if (result) {
        return result
      }
    }
  }
  return {}
}

/**
 * 判断是为空
 * @param value
 * @returns
 */
export function isEmpty(value: any): boolean {
  return value == null || value == '' || value == undefined ? true : false
}

export function getDate(type?: 'day' | 'month' | 'year', number = 0) {
  const nowdate = new Date()
  switch (type) {
    case 'day': //取number天前、后的时间
      nowdate.setTime(nowdate.getTime() + 24 * 3600 * 1000 * number)
      break
    case 'month': //取number月前、后的时间
      nowdate.setMonth(nowdate.getMonth() + number)
      break
    case 'year': //取number年前、后的时间
      nowdate.setFullYear(nowdate.getFullYear() + number)
      break
    default: //取当前时间
      break
  }
  const year = nowdate.getFullYear()
  const month = ('0' + (nowdate.getMonth() + 1)).slice(-2)
  const day = ('0' + nowdate.getDate()).slice(-2)
  return `${year}-${month}-${day}`
}

export function showSugar(v: number) {
  // const { t } = useI18n()
  // switch (v) {
  //   case 0:
  //     return t('options.sugarData.z')
  //   case 30:
  //     return t('options.sugarData.a')
  //   case 50:
  //     return t('options.sugarData.b')
  //   case 70:
  //     return t('options.sugarData.c')
  //   case 100:
  //     return t('options.sugarData.d')
  //   case 120:
  //     return t('options.sugarData.e')
  // }
  return v + '%'
}
export function showCold(v: number) {
  const { t } = useI18n()
  switch (v) {
    case 20:
      return t('options.coldData.a')
    case 10:
      return t('options.coldData.b')
    case 30:
      return t('options.coldData.c')
  }
}

export function showPayWay(v: number) {
  // 50 Terminal，51 payme，52 Uzum，53 Click，54 Alif，55 Card.
  const { t } = useI18n()
  switch (v) {
    case 0:
      return t('home.list.payWayData0')
    case 1:
      return t('home.list.payWayData1')
    case 2:
      return t('home.list.payWayData2')
    case 10:
      return t('home.list.payWayData10')
    case 11:
      return t('home.list.payWayData11')
    case 50:
      return 'Terminal'
    case 51:
      return 'payme'
    case 52:
      return 'Uzum'
    case 53:
      return 'Click'
    case 54:
      return 'Alif'
    case 55:
      return 'Card'
    case 100:
      return 'Telegram'
    case 101:
      return t('home.list.payWayData101')
    case 102:
      return t('home.list.payWayData102')
    case 103:
      return t('home.list.payWayData103')
  }
}
export function showChargeWay(v: number) {
  const { t } = useI18n()
  switch (v) {
    case 0:
      return '充值总额'
    case 1:
      return '现金充值'
    case 2:
      return '网络支付充值'
  }
}

export function showAgentWay(v: number) {
  const { t } = useI18n()
  switch (v) {
    case 1:
      return '货款'
    case 2:
      return '服务费'
    case 3:
      return '运费'
  }
}

export function showSource(v: number) {
  const { t } = useI18n()
  switch (v) {
    case 0:
      return t('home.list.sourceData0')
    case 1:
      return t('home.list.sourceData1')
  }
}

export function showType(v: number) {
  const { t } = useI18n()
  switch (v) {
    case 10:
      return t('home.list.typeData10')
    case 20:
      return t('home.list.typeData20')
    case 30:
      return t('home.list.typeData30')
  }
}

export function showAgentType(v: number) {
  const { t } = useI18n()
  switch (v) {
    case 0:
      return t('home.agent.status0')
    case 10:
      return t('home.agent.status10')
    case 15:
      return t('agent.status15')
    case 20:
      return t('home.agent.status20')
    case 30:
      return t('home.agent.status30')
    case 40:
      return t('home.agent.status40')
    case 100:
      return t('home.agent.status100')
  }
}

export function showName(obj: ApiOrderProductInfo) {
  return localStorage.getItem('localeLang') == 'zhCn' ? obj.productNameZh : obj.productNameRu
}
